﻿// ********************************************************************
//  文件名: MySocket_Udp.cs
//  描述:
//  作者: 胡宇辰
//  创建时间: 2024-3-30
// 
//  修改历史:
// ********************************************************************

using System.Net;
using System.Net.Sockets;

namespace MyApp;

public class MySocket_Udp
{
    static Socket socket;
    private static IPEndPoint _serverEP;
    public static void Enter()
    {
        //客户端利用socket连接服务器
        socket = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);
        socket.Bind(new IPEndPoint(IPAddress.Any, 0));
        _serverEP = new IPEndPoint(IPAddress.Parse("127.0.0.1"), 6324); 
        try
        {
            var sendThread = new Thread(SendMsg);
            sendThread.IsBackground = true;
            sendThread.Start();
        }
        catch (Exception e)
        {
            Console.WriteLine(e);
            throw;
        }
    }

    static void SendMsg()
    {
        byte[] buffer = new byte[1024];
        //向服务器发送数据
        while (true)
        {
            string? str = Console.ReadLine();
            int count = System.Text.Encoding.UTF8.GetBytes(str!, buffer);
            socket.SendTo(buffer, 0, count, SocketFlags.None, _serverEP);
            EndPoint tempEP = _serverEP;
            int len = socket.ReceiveFrom(buffer, SocketFlags.None, ref tempEP);
            string str2 = System.Text.Encoding.UTF8.GetString(buffer, 0, len);
            Console.WriteLine($"Receive from Server:{str2}");
        }
    }
}